package com.daoshu.mds.message.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daoshu.mds.dispatch.entity.MicroGroupEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMemberEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMessageEntity;
import com.daoshu.mds.message.service.IMessageService;
import com.daoshu.mds.message.service.IMicroGroupMemberService;
import com.daoshu.mds.message.service.IMicroGroupMessageService;
import com.daoshu.mds.message.service.IMicroGroupService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements IMessageService {

	/**
     * 消息发送工具
     */
    @Autowired
    private SimpMessagingTemplate template;
    
    @Autowired
    private IMicroGroupMessageService microGroupMessageService;
    @Autowired
    private IMicroGroupMemberService microGroupMemberService;
    @Autowired
	private IMicroGroupService microGroupService;
    
    @Override
    @Async("taskExecutor")
	public void sendMessage(MicroGroupMessageEntity message) {
		message.setCreateTime(new Date());
		if (message.getType() > 0 && StringUtils.isEmpty(message.getPath())) {
			return;
		}
		microGroupMessageService.save(message);
		if (StringUtils.isNotBlank(message.getMicroGroupId())) {
			List<MicroGroupMemberEntity>  members = microGroupMemberService.list(new QueryWrapper<MicroGroupMemberEntity>().lambda()
					.eq(MicroGroupMemberEntity::getMicroGroupId, message.getMicroGroupId()));
			for (MicroGroupMemberEntity member:members) {
				if (StringUtils.isNotBlank(member.getId())) {
                    template.convertAndSend("/microGroupMessage/"+member.getId(), message.toJsonString());
                }
			}

			MicroGroupEntity microGroupEntity = microGroupService.getById(message.getMicroGroupId());
			microGroupEntity.setLastMessageUpdateTime(new Date());
			microGroupService.updateById(microGroupEntity);
		}
	}

	@Override
	@Async("taskExecutor")
	public void sendAlarmMessage(String alarms) {
    	template.convertAndSend("/alarmMessage", alarms);
	}

	@Override
	@Async("taskExecutor")
	public void sendNoticeMessage(MicroGroupMessageEntity message) {
		String channel = message.getCreateId();
		if (StringUtils.isNotBlank(channel)) {
			template.convertAndSend("/notice/" + channel.toString(), JSON.toJSONString(message));
			System.out.println("下线通知……………………………………");
		}
	}
}
